﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using HttpLibrary;
using StockTrader.Broker.IciciDirect;
using StockTrader.Core;
using StockTrader.Utilities;

namespace Experiments
{
    partial class Program
    {
        string stocksDir = @"C:\StockRunFiles\TickFiles\";

        const string URL_GOOG_HISTORICAL = @"http://www.google.com/finance/historical?q=NSE:NIFTY";
        const string URL_GOOG_REALTIMEDATA = @"http://www.google.com/finance/getprices";
        //?q=RELIANCE&x=NSE&i=60&p=5d&f=d,c,o,h,l&df=cpct&auto=1&ts=1266701290218";

        public static void GetRealTimeData1d()
        {
            string outStocksDir = @"C:\StockRunFiles\Google\1d";
            //var symbols = new string[] { ".NSEI", "SBIN", "BANKNIFTY", "SENSEX" };

            var symConfigFile = @"C:\StockRunFiles\Google\GoogleNSE-1min.txt";

            var symbols = File.ReadAllLines(symConfigFile);

            DerivativeSymbolQuote dsq;
            IBroker broker = new IciciDirectBroker("cc", "cc", "07111982");
            //BrokerErrorCode errorCode = broker.GetDerivativeQuote("NIFTY",
            //     InstrumentType.FutureIndex,
            //     new DateTime(2013, 03, 28),
            //     0,
            //     out dsq);


            DateTime time = DateTime.Now;

            var outStocksDayPath = Path.Combine(outStocksDir, time.ToString("ddMMyyyy"));
            var ts = GetTimestamp(DateTime.Now);
            //time = time.AddSeconds(1335591480);
            time = time.AddSeconds(126670129);

            if (!Directory.Exists(outStocksDayPath))
                Directory.CreateDirectory(outStocksDayPath);

            string sym;
            string exch = "NSE";
            string interv = "60";
            string period = "1d";
            string fields = "d,c,o,h,l,v";
            string auto = "1";
            string timeStart = "";

            CookieContainer cookies = new CookieContainer();
            foreach (var symbol in symbols)
            {
                string newFile = Path.Combine(outStocksDayPath, symbol + "-" + time.ToString("ddMMyyyy") + ".txt");

                if (File.Exists(newFile)) continue;

                StringBuilder sb = new StringBuilder(URL_GOOG_REALTIMEDATA);
                sb.AppendFormat("?q={0}{1}&i={2}&p={3}&f={4}&auto={5}{6}",
                    symbol,
                    "",//exch,&x={1}
                    interv,
                    period,
                    fields,
                    auto,
                    ""//"&ts=" + timeStart
                    );

                string data = HttpHelper.GetWebPageResponse(sb.ToString(), null, null, cookies);

                File.AppendAllText(newFile, data);
            }
        }

        public static void StartUrtcc()
        {
            ProcessStartInfo start = new ProcessStartInfo();
            string exeLocation = @"D:\StockData\UTRCC\UtrrcDownloader1.0.0.3.exe";
            // Enter the executable to run, including the complete path 
            start.FileName = exeLocation;

            // Do you want to show a console window? 
            start.WindowStyle = ProcessWindowStyle.Normal;// Hidden;
            start.CreateNoWindow = false;// true;

            using (Process proc = Process.Start(start))
            {
                Console.WriteLine(string.Format("Process # {0} started", exeLocation));
                Console.WriteLine("Download using URTCC, then press any key to process those files....");
                Console.ReadKey();
                proc.Kill();
            }
        }

        public static void ConvertGoogleFormatToMine()
        {
            StartUrtcc();
            Console.WriteLine("Downloading done, now doing conversion of regular and Incremental New symbols....");
            string outStocksDir = @"C:\StockRunFiles\Google\1d";
            string dumpStocksDir = @"C:\StockRunFiles\Google\dump\" + DateTime.Now.Date.ToString("ddMMyyyy");
            var symDirNSE = @"D:\StockData\UTRCC\IEOD\NSEG1min";
            var symDirBSE = @"D:\StockData\UTRCC\IEOD\BSEG1min";

            var symDirNSE1 = @"D:\StockData\UTRCC-Incremental\IEOD\NSEG1min";
            var symDirBSE1 = @"D:\StockData\UTRCC-Incremental\IEOD\BSEG1min";

            if (!Directory.Exists(outStocksDir))
                Directory.CreateDirectory(outStocksDir);

            if (!Directory.Exists(dumpStocksDir))
                Directory.CreateDirectory(dumpStocksDir);

            var symFilesNSE = Directory.EnumerateFiles(symDirNSE, "*", SearchOption.AllDirectories);
            var symFilesBSE = Directory.EnumerateFiles(symDirBSE, "*", SearchOption.AllDirectories);
            StreamWriter sw = null;

            List<string> symFiles = new List<string>(symFilesNSE);
            symFiles.AddRange(symFilesBSE);

            var symFilesNSE1 = Directory.EnumerateFiles(symDirNSE1, "*", SearchOption.AllDirectories);
            var symFilesBSE1 = Directory.EnumerateFiles(symDirBSE1, "*", SearchOption.AllDirectories);
            symFiles.AddRange(symFilesNSE1);
            symFiles.AddRange(symFilesBSE1);

            foreach (var symFile in symFiles)
            {
                Console.WriteLine(symFile);

                string sym = Path.GetFileName(symFile);
                sym = sym.Remove(sym.IndexOf('.')); 

                int i = 0;
                bool isNewFile = true;
                DateTime time = DateTime.MinValue;

                var data = File.ReadAllLines(symFile);

                foreach (var s in data)
                {
                    if (i++ == 0) continue;  // ignore the first line

                    string[] parts = s.Split(',');
                    IFormatProvider culture = new CultureInfo("en-US", true);
                    string dateString = parts[1] + ":" + parts[2];
                    DateTime dt = DateTime.ParseExact(dateString, "yyyyMMdd:HH:mm:ss", culture);

                    if (!MarketUtils.IsTimeAfter915(dt) || MarketUtils.IsTimeAfter330Market(dt)) continue;

                    StringBuilder sb = new StringBuilder("{0},{1},{2},{3},{4},{5}");
                    var line = string.Format(sb.ToString(), dt.ToString("yyyyMMdd:HH:mm:ss"), parts[3], parts[4], parts[5], parts[6], parts[7]);

                    isNewFile = time.Date != dt.Date;
                    if (isNewFile)
                    {
                        time = dt;
                        var outStocksDayPath = Path.Combine(outStocksDir, time.ToString("ddMMyyyy"));

                        if (!Directory.Exists(outStocksDayPath))
                            Directory.CreateDirectory(outStocksDayPath);

                        var fileName = sym + "-" + time.ToString("ddMMyyyy") + ".txt";
                        string newFile = Path.Combine(outStocksDayPath, fileName);

                        if (sw != null)
                        {
                            sw.Dispose();
                            sw = null;
                        }

                        if (File.Exists(newFile))
                        {
                            File.Copy(newFile, Path.Combine(dumpStocksDir, fileName), true);
                            File.Delete(newFile);
                        }
                        sw = new StreamWriter(newFile);
                    }

                    sw.WriteLine(line);
                }

                if (sw != null)
                {
                    sw.Dispose();
                    sw = null;
                }
            }
        }


        //public static void ConvertUrtccFormatToMine()
        //{

        //}

        public static string GetTimestamp(DateTime value)
        {
            return value.ToString("yyyyMMddHHmmssffff");
        }
    }
}